package com.example.manager.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.example.manager.entity.CourseTeaching;
import com.example.manager.entity.Teacher;
import com.example.manager.repository.CourseTeachingRepository;
import com.example.manager.repository.TeacherRepository;


@Service
@Transactional
public class CourseTeachingServiceImpl implements CourseTeachingService{
	
	@Autowired
	private CourseTeachingRepository ctRepository;
	@Autowired
	private TeacherRepository teacherRepo;
	
	@Override
	public String addCourseTeaching(CourseTeaching ct) {
		if(ct.getTeacher()==null||ct.getCourse()==null||ct.getSemester()==null||ct.getYear()==null) {
			return "imcomplete info";
		}
		ctRepository.save(ct);
		return "success";
	}

	@Override
	public String deleteCourseTeaching(Integer id) {
		if(ctRepository.existsById(id)) {
			ctRepository.deleteById(id);
			return "success";
		}
		return "fail";
	}

	@Override
	public String editCourseTeaching(CourseTeaching ct) {
		if(ct.getTeacher()==null||ct.getCourse()==null||ct.getSemester()==null||ct.getYear()==null) {
			return "imcomplete info";
		}
		Integer ctId = ct.getId();
		CourseTeaching ct2 = ctRepository.getOne(ctId);
		ct2.setTeacher(ct.getTeacher());
		ct2.setCourse(ct.getCourse());
		ct2.setSemester(ct.getSemester());
		ct2.setYear(ct.getYear());
		ctRepository.save(ct2);
		return "success";
		
	}

	@Override
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<CourseTeaching> findAllCourseTeaching() {
	
		return ctRepository.findAll();
		
	}

	@Override
	public List<CourseTeaching> getByTeacher(Teacher teacher) {
	
		return ctRepository.getByTeacher(teacher);
	}

	@Override
	public List<CourseTeaching> getByTeacher(String tid) {
		Teacher t = teacherRepo.getOne(tid);
		return ctRepository.getByTeacher(t);
	}

	@Override
	public CourseTeaching getById(Integer id) {
		return ctRepository.getOne(id);
	}
}
